<template>
  <div class="app-container">
    <div class="set-rule">
      <el-form
        :model="ruleData"
        ref="ruleDataForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div class="title"><span style="color: red"> * </span> 条件</div>
        <el-card
          class="box-card"
          shadow="never"
          v-for="(item, index) in ruleData.cardForm"
          :key="index"
        >
          <el-form-item
            label="地区"
            :prop="'cardForm.' + index + '.areaRoiesLenth'"
            :rules="{
              required: true,
              message: '请选择地区',
              trigger: ['blur', 'change'],
            }"
          >
            <el-cascader
              v-model="item.areaRoiesLenth[index]"
              :options="areaProps"
              @change="handleChange(index)"
              @visible-change="(v)=>{handleVisibleChange(v, index)}"
              :placeholder="'请选择可配送的区域' + index"
              clearable
              collapse-tags
              :props="{ multiple: true }"
              :ref="'cascaderAddr' + index"
              class="cascader"
            >
            </el-cascader>
          </el-form-item>
          <div class="box-card-rule">
            <!-- this.ruleData.cardForm[index].areaEcho -->
            <div
              v-if="ruleData.cardForm[index].areaEcho.length > 0"
              class="checked-list"
            >
              <div
                v-for="(val, idx) in JSON.parse(
                  ruleData.cardForm[index].areaEcho
                )"
                :key="idx"
                class="checked-item"
              >
                <span v-if="val.checked">
                  <el-button slot="reference">{{ val.label }}</el-button>
                </span>
                <span v-else>
                  <el-popover
                    placement="right"
                    width="400"
                    popper-class="area_popper"
                    trigger="hover"
                  >
                    <el-button slot="reference"
                      >{{ val.label }}（部分地区）</el-button
                    >
                    <div v-for="(v, i) in val.children" :key="i">
                      <div>
                        <div class="city">{{ v.label }}</div>
                        <div
                          class="third-item"
                          v-for="(val, idx) in v.children"
                          :key="idx"
                        >
                          * {{ val.label }}
                        </div>
                      </div>
                    </div>
                  </el-popover>
                </span>
              </div>
            </div>
            <div v-else>全部可送地区{{ index }}</div>
          </div>
          <el-button class="delete-rule" @click="handleDeleteRules(index)"
            >删除</el-button
          >
        </el-card>
        <el-form-item class="oper-rules">
          <el-button type="primary" @click="addRules(ruleData.cardForm.length)"
            >新增条件</el-button
          >
        </el-form-item>
        <el-form-item class="oper-rules">
          <el-button @click="resetForm">取消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >保存</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import provincialLevel from "@/utils/provincialLevel.js"
import { areaData } from "../mixin/area";

export default {
  mixins:[areaData],
  name: "newRules",
  components: {},

  data() {
    return {
      ruleForm: {
        freightName: "",
        freightStatus: "",
      },
      ruleData: {
        cardForm: [
          {
            freightType: 1,
            price: "",
            areaRoiesLenth: [],
            areaList: [],
            areaEcho: [],
          },
        ],
      },
      templeteId: "",
      flagType: "",
      rules: {
        freightName: [
          { required: true, message: "请输入规则名称", trigger: "blur" },
        ],
        freightStatus: [
          { required: true, message: "请选择启用状态", trigger: "change" },
        ],
      },
      ruleDataForm: {
        areaRoiesLenth: [
          { required: true, message: "请选择包邮地区", trigger: "change" },
        ],
      },
      options: provincialLevel
    };
  },
  filters: {},
  created() {
    // console.log(this.$route.query);
    this.templeteId = this.$route.query.templeteId;
    this.flagType = this.$route.query.type;
  },
  methods: {
    handleVisibleChange(visible, index) {
      if (!visible) {
        return
      }
      this.calcAreaPropsFinal(index)
    },
    calcAreaPropsFinal(index) {
      if (!this.ruleData || !this.ruleData.cardForm) {
        return
      }
      const selectedArea = []
      for (let i = 0; i < this.ruleData.cardForm.length; i++) {
        if (i === index) {
          continue
        }
        const form = this.ruleData.cardForm[i]
        if (!form.areaRoiesLenth[i]) {
          continue
        }
        for (let j = 0; j < form.areaRoiesLenth[i].length; j++) {
          const areaItem = form.areaRoiesLenth[i][j]
          const checkedArea = areaItem[areaItem.length - 1]
          selectedArea.push(checkedArea)
        }
      }
      for (const l1 of this.areaProps) {
        l1.disabled = false
        if (!l1.children) {
          continue
        }
        for (const l2 of l1.children) {
          l2.disabled = false
          if (!l2.children) {
            continue
          }
          for (const l3 of l2.children) {
            l3.disabled = false
            if (selectedArea.includes(l3.value)) {
              l3.disabled = true
            }
          }
        }
      }
    },
    // 新增单个包邮条件
    addRules(val) {
      console.log(val);
      if (this.ruleData.cardForm.length > 4) {
        this.$message.info("最多可增加5个包邮条件");
      } else {
        this.ruleData.cardForm.push({
          freightType: 1,
          areaRoiesLenth: [],
          price: "",
          areaList: [],
          areaEcho: [],
        });
      }
    },

    handleChange(index) {
      let cascaderAddr = this.$refs["cascaderAddr" + index];
      console.log(cascaderAddr[0].checkedNodes);
      cascaderAddr[0].getCheckedNodes();
      let address = cascaderAddr[0].getCheckedNodes();
      let checkedNodeList = address.filter(
        (item) => !(item.parent && item.parent.checked)
      );
      console.log(checkedNodeList);
      let areaList = [];
      address.map((item) => {
        if (item.level == 3) {
          areaList.push({
            provinceId: item.parent.parent.value,
            provinceName: item.parent.parent.label,
            cityId: item.parent.value,
            cityName: item.parent.label,
            districtId: item.value,
            districtName: item.label,
          });
        }
      });
      this.ruleData.cardForm[index].areaList = areaList;

      // 重新拼接选中数据
      const nodeHash = {};
      checkedNodeList.forEach((item) => {
        if (item.level == 1) {
          if (item?.children) {
            let arrObj = [];
            let areaObj = [];
            item.children.forEach((val) => {
              const area3 = [];
              if (val.children) {
                val.children.forEach((val3) => {
                  area3.push({
                    label: val3.label,
                    value: val3.value,
                    checked: val3.checked,
                  });
                });
              }
              arrObj.push({
                label: val.label,
                value: val.value,
                children: area3,
                checked: val.checked,
              });
            });
            nodeHash[item.label] = {
              label: item.label,
              value: item.value,
              checked: item.checked,
              children: arrObj,
            };
          }
        } else if (item.level == 2 && !nodeHash[item.parent.label]) {
          const area3 = [];
          item.children.forEach((val) => {
            area3.push({
              label: val.label,
              value: val.value,
            });
          });
          nodeHash[item.parent.label] = {
            label: item.parent.label,
            value: item.parent.value,
            children: [
              {
                label: item.label,
                value: item.value,
                children: area3,
              },
            ],
            childrenHash: {},
          };
          nodeHash[item.parent.label].childrenHash[item.label] = item.label;
        } else if (item.level == 2 && nodeHash[item.parent.label]) {
          if (!nodeHash[item.parent.label].childrenHash[item.label]) {
            const area3 = [];
            item.children.forEach((val) => {
              area3.push({
                label: val.label,
                value: val.value,
              });
            });
            nodeHash[item.parent.label].children.push({
              label: item.label,
              value: item.value,
              children: area3,
            });
            nodeHash[item.parent.label].childrenHash[item.label] = item.label;
          }
        } else if (item.level == 3 && !nodeHash[item.parent.parent.label]) {
          nodeHash[item.parent.parent.label] = {
            label: item.parent.parent.label,
            value: item.parent.parent.value,
            children: [
              {
                label: item.parent.label,
                value: item.parent.value,
                children: [
                  {
                    label: item.label,
                    value: item.value,
                  },
                ],
              },
            ],
            childrenHash: {},
          };
          nodeHash[item.parent.parent.label].childrenHash[item.parent.label] =
            item.parent.label;
        } else if (item.level == 3 && nodeHash[item.parent.parent.label]) {
          const label = nodeHash[item.parent.parent.label];
          if (item.level == 3 && !label.childrenHash[item.parent.label]) {
            label.children.push({
              label: item.parent.label,
              value: item.parent.value,
              children: [
                {
                  label: item.label,
                  value: item.value,
                },
              ],
            });
            label.childrenHash[item.parent.label] = item.parent.label;
          } else {
            label.children.forEach((i) => {
              if (i.value == item.parent.value) {
                i.children.push({
                  label: item.label,
                  value: item.value,
                });
              }
            });
          }
        }
      });
      this.ruleData.cardForm[index].areaEcho = JSON.stringify(
        Object.values(nodeHash)
      );
    },

    // 删除规则item
    handleDeleteRules(index) {
      // console.log('删除规则'+ index)
      if (this.ruleData.cardForm.length <= 1) {
        this.$message.error("最少需要一个规则");
      } else {
        this.ruleData.cardForm.splice(index, 1);
      }
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleData.cardForm) {
            for (let key in this.ruleData.cardForm) {
              this.ruleData.cardForm[key].areaRoiesLenth = JSON.stringify(
                this.ruleData.cardForm[key].areaRoiesLenth.flat()
              );
            }
          }
          const params = {
            ...this.ruleForm,
            list: [...this.ruleData.cardForm],
          };
          console.log(params);
          // return
        }
      });
    },
    resetForm() {
      this.$refs["ruleDataForm"].resetFields();
      this.$refs["ruleForm"].resetFields();
      this.$router.go(-1);
    },
    getTempleteDetail(templeteId) {
      selectGoodsFreightInfo({ templeteId }).then((res) => {
        this.ruleForm.freightName = res.result.freightName;
        this.ruleForm.freightStatus = res.result.freightStatus;
        this.ruleData.cardForm = res.result.freightList;
        for (let index in this.ruleData.cardForm) {
          const area = [];
          for (let i = 0; i <= index; i++) {
            if (index == i) {
              area.push(
                JSON.parse(this.ruleData.cardForm[index].areaRoiesLenth)
              );
            } else {
              area.push([]);
            }
          }
          this.ruleData.cardForm[index].areaRoiesLenth = area;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
::v-deep input[type="number"] {
  -moz-appearance: textfield;
}
.app-container {
  width: 800px;
  .rule-input {
    :deep(.el-input__inner) {
      width: 320px;
    }
  }
}
.set-rule {
  display: flex;
  flex-direction: column;
  .title {
    width: 100px;
    margin-left: 25px;
  }
}
.box-card {
  width: 100%;
  display: flex;
  padding-left: 25px;
  margin: 10px 0 15px 60px;
  position: relative;
  .condition {
    :deep(.el-form-item__content) {
      display: flex;
      flex-direction: column;
      padding-top: 11px;
      .tip-rule {
        margin-top: 10px;
      }
    }
  }
  .el-card {
    margin-left: 15px;
    width: 600px;
    .el-card__body {
      padding: 0;
    }
  }
  .tip-rule {
    width: 330px;
  }
  .tips {
    font-size: 14px;
    color: #ccc;
  }
}
.box-card-rule {
  width: 500px;
  border: 1px solid #e6ebf5;
  min-height: 60px;
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
}
.oper-rules {
  :deep(.el-form-item__content) {
    margin-left: 60px !important;
  }
}
.delete-rule {
  position: absolute;
  top: 20px;
  right: 20px;
}
.checked-list {
  display: flex;
  flex-wrap: wrap;
  .checked-item {
    margin: 5px;
  }
}
.city {
  font-size: 16px;
  color: #000;
}
.third-item {
  margin: 2px 0 2px 20px;
}
</style>
